package io.github.bloquesoft.entity.clazz.value;

import io.github.bloquesoft.entity.clazz.ClassPojoPropertyDefinition;
import io.github.bloquesoft.entity.value.PojoPropertyValue;

import java.lang.reflect.Field;

public class ObjectPojoPropertyValue implements PojoPropertyValue {

    private final ClassPojoPropertyDefinition classEntityPojoProperty;

    private final ObjectEntityValue parent;

    public ObjectPojoPropertyValue(ClassPojoPropertyDefinition classEntityPojoProperty, ObjectEntityValue parent) {
        this.classEntityPojoProperty = classEntityPojoProperty;
        this.parent = parent;
    }

    @Override
    public Object getValue() {
        if (!this.parent.isNullValue()) {
            Field field = this.classEntityPojoProperty.getField();
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            try {
                return field.get(this.parent.getValue());
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public void setValue(Object value) {
        if (this.parent.isNullValue()) {
            throw new IllegalArgumentException("Could set value for a null Object value entity");
        }
        else {
            Field field = this.classEntityPojoProperty.getField();
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            try {
                field.set(this.parent.getValue(), value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public Boolean isNullValue() {
        return this.getValue() == null;
    }

    @Override
    public String getPropertyId() {
        return this.classEntityPojoProperty.getId();
    }
}